<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/18 下午3:01
 * +-------------------------------------------------------------
 */

namespace app\common\middleware;

use app\common\service\AuthService;
use app\common\traits\JsonTrait;
use Closure;

class CheckAuth
{
    use JsonTrait;

    public function handle($request, Closure $next)
    {
        $userInfo = $request->userInfo;
        $appName  = app('http')->getName();
        if (empty($userInfo)) return $next($request);
        $commonConfig = config('common');
        // 获取当前管理员ID
        $uid = $userInfo['id'];
        // 获取当前管理员角色ID
        $authService = app(AuthService::class, ['uid' => $uid, 'app_name' => $appName]);
        // 获取当前控制器(菜单)
        $currentController = parse_name($request->controller());
        // 获取当节点
        $currentNode = $authService->getCurrentNode();
        // 检查是否有权限访问当前路由
        if (!in_array($currentController, $commonConfig['no_auth_controller']) && !in_array($currentNode, $commonConfig['no_auth_node'])) {
            // 验证权限
            $check = $authService->checkNode($currentNode);
            if (!$check) return $this->errPermission();
        }
        return $next($request);
    }
}